package com.meihuayishu.backend.common;

import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Builder;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.time.Instant;
import java.util.UUID;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiResponse<T> {
    private boolean success;
    private int code;
    private String message;
    private T data;
    private ErrorInfo error;
    private String timestamp;
    private String requestId;
    
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public static class ErrorInfo {
        private String type;
        private Object details;
    }
    
    public static <T> ApiResponse<T> success(T data) {
        return ApiResponse.<T>builder()
                .success(true)
                .code(200)
                .message("操作成功")
                .data(data)
                .timestamp(Instant.now().toString())
                .requestId(generateRequestId())
                .build();
    }
    
    public static <T> ApiResponse<T> success(T data, String message) {
        return ApiResponse.<T>builder()
                .success(true)
                .code(200)
                .message(message)
                .data(data)
                .timestamp(Instant.now().toString())
                .requestId(generateRequestId())
                .build();
    }
    
    public static <T> ApiResponse<T> error(int code, String message) {
        return ApiResponse.<T>builder()
                .success(false)
                .code(code)
                .message(message)
                .timestamp(Instant.now().toString())
                .requestId(generateRequestId())
                .build();
    }
    
    public static <T> ApiResponse<T> error(int code, String message, String errorType, Object errorDetails) {
        ErrorInfo errorInfo = ErrorInfo.builder()
                .type(errorType)
                .details(errorDetails)
                .build();
                
        return ApiResponse.<T>builder()
                .success(false)
                .code(code)
                .message(message)
                .error(errorInfo)
                .timestamp(Instant.now().toString())
                .requestId(generateRequestId())
                .build();
    }
    
    private static String generateRequestId() {
        return "req_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
}